<template>
    <div class="problem">
        <div class="content">
            <div class="left">
                <div class="ipt">
                    <Input search enter-button placeholder="请输入关键字" v-show="inputShow" v-model="keyword" clearable/>
                    <Input v-show="inputShow" search placeholder="请输入关键字" style="opacity:0;position: absolute;top:-9999px;width:1px;"/>
                </div>
                <div class="tree">
                    <el-tree ref="treeBox" :data="treeData" :render-content="renderContent" :default-expanded-keys="expandedKeys" :props="defaultProps" :filter-node-method="filterNode" @node-click="getTreeId" node-key="issueTypeId"></el-tree>
                </div>
                <div class="btn">
                    <el-button class="addClass" @click="updateRow(5)" type="primary" size="small" plain v-if="auth.isType">类别管理
                    </el-button>
                </div>
            </div>
            <div class="right">
                <el-button v-if="!detailAddFlag&&auth.isAdd" @click="updateRow(6)" type="primary" size="small" plain>
                    + 添加明细
                </el-button>
                <div class="table">
                    <el-table :data="issueList" style="width: 100%">
                        <el-table-column prop="content" label="检查内容">
                            <template slot-scope="scope">
                                <Tooltip transfer :content="scope.row.content" placement="top-start" max-width='200'>
                                    <p style="width:200px;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;cursor: pointer;">
                                        {{ scope.row.content }}
                                    </p>
                                </Tooltip>
                            </template>
                        </el-table-column>
                        <el-table-column prop="require" label="整改要求">
                            <template slot-scope="scope">
                                <Tooltip transfer :content="scope.row.require" placement="top-start" max-width='300'>
                                    <p style="width:200px;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;cursor: pointer;">
                                        {{ scope.row.require }}
                                    </p>
                                </Tooltip>
                            </template>
                        </el-table-column>
                        <el-table-column prop="duration" label="整改期限（天）"></el-table-column>
                        <el-table-column prop="enableFlag" label="状态">
                            <template slot-scope="scope">
                                <div v-if="scope.row.enableFlag == 1">
                                    <!-- <Icon type="md-checkmark-circle" style="color:#ccc;font-size: 18px;"/> -->
                                    <span class="green">已启用</span>
                                </div>
                                <div v-if="scope.row.enableFlag==0">
                                    <!-- <img src="../../assets/images/safety/problem/disable.png" alt="" width="15" height="15" style="vertical-align: middle;"> -->
                                    <span class="red">已禁用</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="150px">
                            <template slot-scope="scope">
                                <el-button v-if="auth.isEdit" @click.native.prevent="updateRow(8,scope.row)" type="text" size="small">
                                    编辑
                                </el-button>

                                <el-button v-if="scope.row.enableFlag == 1&&auth.isEnable" style="color:red" @click.native.prevent="updateRow(7,scope.row)" type="text" size="small">
                                    禁用
                                </el-button>

                                <el-button v-if="scope.row.enableFlag == 0&&auth.isEnable" style="color:red" @click.native.prevent="updateRow(7,scope.row)" type="text" size="small">
                                    启用
                                </el-button>
                                <el-button v-if="auth.isDelete" style="color:red" @click.native.prevent="issueRemoveRow(scope.row)" type="text" size="small">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="clearfix" v-show="issueList.length>0">
                    <div class="float-right">
                        <Page v-if="totalCount" style="margin: 20px 0;text-align: right;" :current="current" :total="totalCount" :page-size="10" show-elevator show-total @on-change="pageChange"></Page>
                    </div>
                </div>
            </div>
        </div>
        <Modal v-model="deleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(8)" type="info" size="small" plain>取消</el-button>
                <el-button @click="detele" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
        <Modal v-model="issueDeleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(5)" type="info" size="small" plain>取消</el-button>
                <el-button @click="issueDetele" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
        <Modal v-model="enableModal" title="状态编辑" width="360px;" :mask-closable="false">
            <div style="margin:10px" v-if="enable!=1">确定禁用这条数据吗？</div>
            <div style="margin:10px" v-else>确定启用这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(6)" type="info" size="small" plain>取消</el-button>
                <el-button @click="enableBtn" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
        <Modal v-model="modal" :title="isAdd?'添加明细':'编辑明细'" :mask-closable="false">
            <div>
                <div class="item2">
                    <i class="tip">*</i>
                    <span>整改期限:</span>
                    <Input v-model.number="timeLimit" :maxlength="3" placeholder="请输入整改期限" style="width: 330px"/>
                    <i style="font-style:normal;margin-left:5px;" clearable>天</i>

                </div>
                <div class="item2 myItem">
                    <i class="tip">*</i>
                    <span>检查内容:</span>
                    <Input v-model="content" type="textarea" :maxlength="50" style="width:350px" :autosize="{minRows: 2}" placeholder="请输入检查内容" clearable/>
                </div>
                <div class="item2 myItem">
                    <i class="tip">*</i>
                    <span>整改要求:</span>
                    <Input v-model="requirements" type="textarea" :maxlength="200" style="width:350px" :autosize="{minRows: 8}" placeholder="请输入整改要求" clearable/>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(7)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submitBtn(10)" type="primary" size="small" plain v-preventReClick="1500">保存
                </el-button>
            </div>
        </Modal>
        <Modal v-model="classModal" title="添加类别" width="900px" :mask-closable="false" footer-hide>
            <div class="addClassModal">
                <el-button type="primary" v-if="!isSonFlag" @click="updateRow(4)" size="small" plain style="margin-left:2%;margin-bottom:20px;">
                    + 添加类别
                </el-button>
                <div class="classAdd" v-show="isClassAdd">
                    <div class="left">
                        <div class="item">
                            <span class="tip" style="color:red">*</span>
                            <span style="width:120px;text-align:right;">编码 ：</span>
                            <el-input :maxlength="4" placeholder="请输入编码" style="width: 300px;height:40px;" v-model="classCode">
                                <template slot="prepend" v-if="isSonFlag&&parentCode!=null&&parentCode!=''">
                                    {{ parentCode }}
                                </template>
                            </el-input>
                        </div>
                        <div class="item">
                            <span class="tip" style="color:red">*</span>
                            <span style="width:120px;text-align:right;">类别名称：</span>
                            <el-input :maxlength="20" placeholder="请输入类别名称" style="width: 300px;height:40px;" v-show="inputShow" v-model="className"></el-input>
                            <el-input placeholder="请输入类别名称" style="opacity:0;position: absolute;top:-9999px;width:1px;" v-show="inputShow"></el-input>
                            <div class="item">
                                <el-button @click="cancel(9)" type="info" size="small" plain>取消</el-button>
                                <el-button @click="submitAll" type="primary" size="small" plain v-preventReClick="1500">
                                    确定
                                </el-button>
                            </div>
                        </div>

                    </div>

                </div>
                <div class="table" style="width:96%;margin:0 auto;">
                    <el-table :data="treeData" height='500' border style="width: 100%" row-key="issueTypeId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                        <el-table-column label="编码" prop="code"></el-table-column>
                        <el-table-column label="名称" prop="name"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button @click.native.prevent="updateRow(10, scope.row)" type="text" size="small" v-preventReClick="1500">
                                    新建下级
                                </el-button>
                                <el-button @click.native.prevent="updateRow(9, scope.row)" type="text" size="small" v-preventReClick="1500">
                                    编辑
                                </el-button>
                                <el-button style="color:red" @click.native.prevent="removeRow(scope.row)" type="text" size="small">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- <div slot="footer">
                <el-button @click="cancel(10)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submitAll" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div> -->
        </Modal>
    </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {toTree, trans} from "@/sever/config.js";
import {
    getIssueTypeList,
    getIssueTypeAdd,
    getIssueTypeEdit,
    getIssueTypeDel,
    getIssueList,
    getIssueAdd,
    getIssueEdit,
    getIssueEnable,
    getIssueDel
} from '@/api/safety'

export default {
    components: {Treeselect},
    data() {
        return {
            expandedKeys: [0],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            classAddFlag: false,
            detailAddFlag: false,
            enable: "",
            issueId: "",
            parentCode: "",
            isSonFlag: false,
            pid: "",
            classCode: '',
            className: '',
            keyword: "",
            inputShow: false,
            isClassAdd: false,
            classModal: false,
            requirements: "",
            content: "",
            timeLimit: "",
            totalCount: "",
            current: 1,
            pageNum: 1,
            pageSize: 10,
            modal: false,
            isAdd: true,
            deleteModal: false,
            enableModal: false,
            issueDeleteModal: false,
            treeData: [],
            issueList: [],
            list: [],
            projectId: "",
            classList: [],
            auth:{
                isType:false,
                isAdd: false,
                isEdit:false,
                isEnable: false,
                isDelete:false,
            }, 
            btnList:[] //权限列表
        };
    },
    methods: {
        initAuth(){
            this.auth.isType = this.btnList.includes('safety/problem/type')
            this.auth.isAdd = this.btnList.includes('safety/problem/add')
            this.auth.isEdit = this.btnList.includes('safety/problem/edit')
            this.auth.isEnable = this.btnList.includes('safety/problem/enable')
            this.auth.isDelete = this.btnList.includes('safety/problem/delete')
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        getIssueAllList() {
            let params = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                issueTypeId: this.issueTypeId
            };
            getIssueList(params)
                .then(res => {
                    if (res.code == 200) {
                        this.issueList = res.data.list;
                        this.totalCount = res.data.total;

                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        pageChange(index) {
            this.pageNum = index;
            this.getIssueAllList();
        },
        getIssueTypeAll() {
            let parmas = {
                deptId: this.projectId,
                keyword: '',
            }
            getIssueTypeList(parmas)
                .then(res => {
                    if (res.code == 200) {
                        if(res.data.list.length > 0){
                            this.list = res.data.list;
                            this.treeData = trans(this.list);
                            this.issueTypeId = this.treeData[0].issueTypeId;
                        }else{
                            this.treeData = [];
                            this.issueTypeId = '';
                        }
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        getTreeId(index) {
            this.issueTypeId = index.issueTypeId;
            if (index.children) {
                this.detailAddFlag = true;
            } else {
                this.detailAddFlag = false;
            }
            this.getIssueAllList();
        },
        issueRemoveRow(row) {
            this.issueDeleteModal = true;
            this.issueId = row.issueId;
        },
        removeRow(row) {
            this.deleteModal = true;
            this.issueTypeId = row.issueTypeId;
        },
        enableBtn() {
            let params = {
                enable: this.enable,
                issueId: this.issueId,
            }
            getIssueEnable(params)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.enable = '';
                        this.issueId = '';
                        this.getIssueAllList();
                        this.enableModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                })
        },
        detele() {
            getIssueTypeDel(this.issueTypeId)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getIssueTypeAll();
                        this.deleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        issueDetele() {
            getIssueDel(this.issueId)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getIssueAllList();
                        this.issueDeleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        cancel(type) {
            if (type == 10) {
                this.classModal = false;
                this.isSonFlag = false;
                this.isClassAdd = false;
                this.className = '';
                this.classCode = '';
                this.pid = '';
            } else if (type == 9) {
                this.isSonFlag = false;
                this.isClassAdd = false;
                this.className = '';
                this.classCode = '';
                this.pid = '';
            } else if (type == 8) {
                this.deleteModal = false;
                this.issueTypeId = "";
            } else if (type == 7) {
                this.modal = false;
                this.content = '';
                this.requirements = '';
                this.timeLimit = '';
            } else if (type == 6) {
                this.enableModal = false;
                this.enable = '';
                this.issueId = '';
            } else if (type == 5) {
                this.issueDeleteModal = false;
                this.issueId = '';
            }
        },
        updateRow(type, row, rows) {
            if (type == 10) {
                this.pid = row.issueTypeId;
                this.parentCode = row.code;
                this.classCode = '';
                this.className = '';
                this.isSonFlag = true;
                this.isClassAdd = true;
                this.isAdd = true;
            } else if (type == 9) {
                this.pid = row.issueTypeId;
                let code = row.code.split(".")
                let parentCode = '';
                for (let i = 0; i < code.length - 1; i++) {
                    parentCode += code[i] + ',';
                }
                this.isSonFlag = true;
                this.isClassAdd = true;
                this.parentCode = parentCode;
                this.classCode = code[code.length - 1];
                this.className = row.name;
                this.isAdd = false;
            } else if (type == 8) {
                this.modal = true;
                this.content = row.content;
                this.timeLimit = row.duration;
                this.requirements = row.require;
                this.issueId = row.issueId;
                this.isAdd = false;
            } else if (type == 7) {
                this.enableModal = true;
                this.enable = row.enableFlag == 1 ? '0' : '1';
                this.issueId = row.issueId;
            } else if (type == 6) {
                this.modal = true;
                this.isAdd = true;
                this.content = "";
                this.timeLimit = "";
                this.requirements = "";
                this.issueId = "";

            } else if (type == 5) {
                this.classModal = true;
                this.isClassAdd = false;
                this.classCode = '';
                this.className = '';
                this.isSonFlag = false;
                this.parentCode = "";
            } else if (type == 4) {
                this.isClassAdd = true;
                this.isSonFlag = true;
                this.isAdd = true;
                this.parentCode = "";
                this.pid = "";
            }

        },
        submitAll() {
            if (this.classCode === '') {
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;
            } else {
                let reg = /^[0-9]*$/;
                if (!reg.test(this.classCode)) {
                    this.$Modal.warning({
                        title: "提示",
                        content: "编码格式错误"
                    });
                    return;
                }
            }

            if (this.className == '') {
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;
            }
            if (this.isAdd) {
                let params = {
                    deptId: this.projectId,
                    pid: this.pid,
                    code: this.classCode,
                    name: this.className
                };
                getIssueTypeAdd(params)
                    .then(res => {
                        if (res.code == 200) {
                            this.success();
                            this.getIssueTypeAll();
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            } else {
                let params = {
                    issueTypeId: this.pid,
                    name: this.className,
                    code: this.classCode,
                };
                getIssueTypeEdit(params)
                    .then(res => {
                        if (res.code == 200) {
                            this.success();
                            this.getIssueTypeAll();
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            }
        },
        submitBtn(type) {
            if (this.content == '' || this.requirements == '' || this.timeLimit == '') {
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;

            }
            if (typeof this.timeLimit != 'number') {
                this.$Modal.warning({
                    title: "提示",
                    content: "请输入正确的时间"
                });
                return;
            }
            if (this.isAdd) {
                let params = {
                    issueTypeId: this.issueTypeId,
                    content: this.content,
                    require: this.requirements,
                    duration: Number(this.timeLimit)
                }
                getIssueAdd(params).then((res) => {
                    if (res.code == 200) {
                        this.modal = false;
                        this.content = '';
                        this.requirements = '';
                        this.timeLimit = '';
                        this.success();
                        this.getIssueAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch((err) => {
                    console.log(err)
                });
            } else {
                let params = {
                    issueId: this.issueId,
                    content: this.content,
                    require: this.requirements,
                    duration: Number(this.timeLimit)
                }
                getIssueEdit(params).then((res) => {
                    if (res.code == 200) {
                        this.modal = false;
                        this.content = '';
                        this.requirements = '';
                        this.timeLimit = '';
                        // this.deptId = this.deptpid;
                        this.success();
                        this.getIssueAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch((err) => {
                    console.log(err)
                });
            }
        },
        success() {
            this.$Message.success("操作成功");
            this.isSonFlag = false;
            this.isClassAdd = false;
            this.classCode = '';
            this.className = '';
            this.pageNum = 1;
            this.isAdd = true;
        },
        getSearch() {
            this.getIssueTypeAll()
        },
        issueTypeTreeExpand(data) {
            data.forEach(obj => {
                if (obj.name.indexOf(this.keyword) != -1) {
                    this.expandedKeys.push(obj.issueTypeId)
                }
                if (obj.children instanceof Array) {
                    obj.children.forEach(v => {
                        if (v.name.indexOf(this.keyword) != -1) {
                            this.expandedKeys.push(obj.issueTypeId)
                        }
                    })
                    this.issueTypeTreeExpand(obj.children)
                }
            })
            return data
        },
        renderContent(h, {node, data, store}) {
            return (
                <span class="custom-tree-node">
                <span title={node.label}>{node.label}</span>
            </span>);
        },
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        }
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.projectId = val.deptId;
                // this.deptName = val.name;
                this.pageNum = 1;
                this.current = 1;
                this.getIssueTypeAll();

            }
        },
        keyword(val){
            this.$refs.treeBox.filter(val);
        }
    },
    mounted() {
        this.projectId = this.$store.state.porjectObject.deptId;
        this.getIssueTypeAll();
        this.btnList = JSON.parse(localStorage.getItem("arr"));//localStorage当中的arr项存取的是按钮权限列表
        this.initAuth() //初始化权限
        // this.getIssueAllList();
        setTimeout(() => {
            this.inputShow = true;
        }, 1)
    }
};
</script>

<style lang="less" scoped>
@import "./../../assets/style/themeBase.less";
@import "../../assets/style/qualityAndSafety/problem.less";

</style>
